# Contributor: Oleg A. Khlybov <fougas@mail.ru>

_realname=scalapack
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=2.2.0
pkgrel=1
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64')
pkgdesc="Scalable Linear Algebra PACKage (mingw-w64)"
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         $([[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]] || echo "${MINGW_PACKAGE_PREFIX}-gcc-libgfortran")
         "${MINGW_PACKAGE_PREFIX}-openblas"
         "${MINGW_PACKAGE_PREFIX}-msmpi")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-fc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
license=('LGPL')
url="https://www.netlib.org/scalapack"
source=("https://www.netlib.org/${_realname}/${_realname}-${pkgver}.tgz"
        '0003-force-single-lib.patch'
        '0004-fix-pc.patch')
sha256sums=('40b9406c20735a9a3009d863318cb8d3e496fb073d201c5463df810e01ab2a57'
            '954c22f1107a254a46400a0014f17af9c5b8877f0034793e2c6781eafafa8225'
            '9f791fdb6a6d59cd86caa53cec62a1a6dbb2f6f31bd16f8320864615695e175e')

prepare() {
  cd "${srcdir}/${_realname}-${pkgver}"
  for p in ${source[*]:1}; do
    patch -p1 -i "${srcdir}/$p"
  done
}

build() {
  declare -a _btype
  if check_option "debug" "y"; then
    _btype=Debug
  else
    _btype=Release
  fi

  export FC=mpifort
  if [[ ${MINGW_PACKAGE_PREFIX} != *-clang-* ]]; then
    export FFLAGS="-fallow-argument-mismatch"
  fi

  mkdir -p build-${MSYSTEM}s && cd build-${MSYSTEM}s
  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    ${MINGW_PREFIX}/bin/cmake \
      -G"Ninja" \
      -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
      -DCMAKE_BUILD_TYPE=${_btype} \
      -DBUILD_SHARED_LIBS=OFF \
      -DSCALAPACK_BUILD_TESTS=OFF \
      ../${_realname}-${pkgver}
  ${MINGW_PREFIX}/bin/cmake --build .

  cd "${srcdir}"
  mkdir -p build-${MSYSTEM} && cd build-${MSYSTEM}
  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    ${MINGW_PREFIX}/bin/cmake \
      -G"Ninja" \
      -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
      -DCMAKE_BUILD_TYPE=${_btype} \
      -DBUILD_SHARED_LIBS=ON \
      -DSCALAPACK_BUILD_TESTS=OFF \
      ../${_realname}-${pkgver}
  ${MINGW_PREFIX}/bin/cmake --build .
}

package() {
  # FIXME proper cmake configuration
  cd "${srcdir}/build-${MSYSTEM}s"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --install .
  cd "${srcdir}/build-${MSYSTEM}"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --install .
  cd "${pkgdir}/${MINGW_PREFIX}" && mv Testing bin
}
